import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'

// 获取实验列表
export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)

    if (!session?.user) {
      return NextResponse.json({ error: '未登录' }, { status: 401 })
    }

    console.log(`获取实验列表，用户: ${session.user.email}，角色: ${session.user.role}`)
    
    // 所有用户（包括学生）都可以查看实验列表
    const experiments = await prisma.experiment.findMany({
      include: {
        stages: true,
        createdBy: {
          select: {
            name: true,
            email: true,
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
    })
    
    console.log(`获取到${experiments.length}个实验`)
    
    if (experiments.length === 0) {
      console.log('警告: 返回的实验列表为空')
    } else {
      console.log('实验列表第一项:', { 
        id: experiments[0].id, 
        title: experiments[0].title,
        stagesCount: experiments[0].stages?.length || 0
      })
    }

    // 获取当前用户的实验提交记录
    if (session.user.role === 'STUDENT') {
      const userSubmissions = await prisma.experimentSubmission.findMany({
        where: {
          studentId: session.user.id,
        },
        select: {
          experimentId: true,
          status: true,
        }
      })

      // 将提交状态添加到实验列表中
      const experimentsWithStatus = experiments.map(exp => {
        const submission = userSubmissions.find(sub => sub.experimentId === exp.id)
        return {
          ...exp,
          userSubmissionStatus: submission?.status || null
        }
      })

      return NextResponse.json(experimentsWithStatus)
    }

    return NextResponse.json(experiments)
  } catch (error) {
    console.error('获取实验列表失败:', error)
    return NextResponse.json(
      { error: '获取实验列表失败' },
      { status: 500 }
    )
  }
}

// 创建新实验
export async function POST(req: NextRequest) {
  try {
    console.log('开始创建实验流程')
    const session = await getServerSession(authOptions)
    console.log('会话信息:', session?.user)

    if (!session?.user) {
      console.log('未登录状态，拒绝创建实验')
      return NextResponse.json({ error: '未登录，请先登录' }, { status: 401 })
    }

    const { id, email, role } = session.user
    
    if (!email) {
      console.log('用户邮箱缺失')
      return NextResponse.json({ error: '用户信息不完整' }, { status: 400 })
    }

    // 检查用户是否存在，如果不存在则根据session信息创建
    let user = await prisma.user.findUnique({
      where: { email: email },
    })
    
    console.log('数据库查询用户结果:', user)

    if (!user) {
      try {
        console.log('用户不存在，尝试创建新用户')
        user = await prisma.user.create({
          data: {
            id: id || undefined,  // 如果ID存在则使用，否则让Prisma生成
            email: email,
            name: session.user.name || email.split('@')[0],
            role: role || 'STUDENT',
            password: 'placeholder', // 实际应用中应当使用安全的密码处理
          }
        })
        console.log('已创建新用户:', user)
      } catch (createError) {
        console.error('创建用户失败:', createError)
        return NextResponse.json({ 
          error: '找不到用户记录且无法创建新用户，请联系管理员' 
        }, { status: 500 })
      }
    }

    // 检查用户权限
    if (user.role !== 'TEACHER' && user.role !== 'ADMIN') {
      console.log('权限不足，需要教师或管理员权限')
      return NextResponse.json({ error: '权限不足，只有教师和管理员能创建实验' }, { status: 403 })
    }

    const data = await req.json()
    console.log('接收到的实验数据:', { ...data, stages: `${data.stages?.length || 0}个阶段` })
    const { title, description, startTime, endTime, allowLateSubmission, stages, authorizedStudents } = data

    // 验证必要字段
    if (!title || !startTime || !endTime) {
      console.log('缺少必要字段')
      return NextResponse.json({ error: '缺少必要参数：标题、开始时间和结束时间都必须提供' }, { status: 400 })
    }

    console.log('开始创建实验记录，createdById:', user.id)
    
    try {
      // 使用事务创建实验和相关数据
      const experimentWithDetails = await prisma.$transaction(async (tx) => {
        // 创建实验基本信息
        const createdExperiment = await tx.experiment.create({
          data: {
            title,
            description: description || '',
            content: JSON.stringify({}), // 确保是字符串格式
            startTime: new Date(startTime),
            endTime: new Date(endTime),
            allowLateSubmission: allowLateSubmission || false,
            createdById: user.id,
          },
        })
        
        console.log(`实验基本信息已创建，ID: ${createdExperiment.id}`)
        
        // 创建实验阶段
        if (stages && Array.isArray(stages)) {
          console.log(`处理${stages.length}个实验阶段`)
          
          for (let i = 0; i < stages.length; i++) {
            const stage = stages[i]
            try {
              await tx.experimentStage.create({
                data: {
                  experimentId: createdExperiment.id,
                  title: stage.title,
                  description: stage.description || '',
                  type: stage.type,
                  order: i + 1,
                  content: typeof stage.content === 'string' 
                    ? stage.content 
                    : JSON.stringify(stage.content || {}),
                }
              })
              console.log(`已创建阶段 ${i+1}/${stages.length}: ${stage.title}`)
            } catch (stageError) {
              console.error(`创建阶段 ${i+1} 失败:`, stageError)
              throw new Error(`创建阶段 "${stage.title}" 失败: ${stageError instanceof Error ? stageError.message : '未知错误'}`)
            }
          }
        }
        
        // 处理授权学生
        if (authorizedStudents && authorizedStudents.length > 0) {
          console.log(`处理${authorizedStudents.length}个授权学生`)
          
          try {
            await tx.experimentAuthorization.createMany({
              data: authorizedStudents.map((studentId: string) => ({
                experimentId: createdExperiment.id,
                studentId,
              })),
            })
            console.log(`已创建${authorizedStudents.length}个授权关系`)
          } catch (authError) {
            console.error('创建授权关系失败:', authError)
            throw new Error(`创建授权关系失败: ${authError instanceof Error ? authError.message : '未知错误'}`)
          }
        }
        
        // 返回完整的实验信息
        return tx.experiment.findUnique({
          where: { id: createdExperiment.id },
          include: {
            stages: true,
            createdBy: {
              select: {
                id: true,
                name: true,
                email: true
              }
            },
            authorizedExperiments: {
              include: {
                student: {
                  select: {
                    id: true,
                    name: true,
                    email: true,
                  }
                }
              }
            }
          },
        })
      })
      
      if (!experimentWithDetails) {
        throw new Error('实验创建失败，未返回实验详情');
      }
      console.log('实验创建成功:', experimentWithDetails.id)
      console.log('已授权学生数量:', experimentWithDetails.authorizedExperiments?.length || 0)
      return NextResponse.json(experimentWithDetails)
    } catch (dbError) {
      console.error('数据库操作失败:', dbError)
      return NextResponse.json(
        { error: '创建实验失败: ' + (dbError instanceof Error ? dbError.message : '未知数据库错误') },
        { status: 500 }
      )
    }
  } catch (error) {
    console.error('创建实验失败:', error)
    return NextResponse.json(
      { error: '创建实验失败: ' + (error instanceof Error ? error.message : '未知错误') },
      { status: 500 }
    )
  }
} 